package cn.yunhe.controllor;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;

import cn.yunhe.entity.Goods;
import cn.yunhe.entity.Page;
import cn.yunhe.service.PageService;

public class PageController extends ActionSupport {
	/**
	 * page控制器
	 */
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private PageService ps;

	/*
	 * public String initPage() {
	 * ServletActionContext.getResponse().setCharacterEncoding("utf-8");
	 * ServletActionContext.getResponse().
	 * setContentType("text/html; charset=utf-8");
	 * 
	 * int currentPage = 1; Page<Goods> page = null;
	 * 
	 * page = ps.getPage(currentPage);
	 * ServletActionContext.getRequest().setAttribute("page", page); return
	 * "success";
	 * 
	 * }
	 */

	public String initPage() {
		return "success";
	}

	public void initFirstPage() {
		ServletActionContext.getResponse().setCharacterEncoding("utf-8");
		ServletActionContext.getResponse().setContentType("text/html; charset=utf-8");
		String currentPage_s = ServletActionContext.getRequest().getParameter("currentPage");
		int currentPage = Integer.parseInt(currentPage_s);
		PrintWriter out = null;
		// int currentPage = 1;
		Page<Goods> page = null;
		HttpServletResponse response = ServletActionContext.getResponse();

		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		page = ps.getPage(currentPage);
		JSONObject page1 = new JSONObject();
		page1.put("page", page);

		out.print(JSON.toJSONString(page1));
		out.flush();
		out.close();

	}

	public String addGoods() {

		System.out.println("-------增加商品名称");

		return "success";
	}
	
	//测试上传
	public String testup(){
		System.out.println("-------测试商品上传1：");
		return "success";
	}
	//测试上传1
	public String testup1(){
		System.out.println("-------测试商品上传2：");
		HttpServletRequest request = ServletActionContext.getRequest();
		String path = request.getSession().getServletContext().getRealPath("/image");
		System.out.println("path:"+path);
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(new File(path));
		factory.setSizeThreshold(1024000);
		ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setSizeMax(10240);
		System.out.println("没有毛病吧");
		try {
			List<FileItem> list = sfu.parseRequest(request);
			for (FileItem item : list) {
				if (item.isFormField()) {// 判断是否是文件流
					// 判断字段名，并获得各个表单项的值
					System.out.println("表单项名称：" + item.getFieldName());
					
				} else{//文件表单字段，获取上传文件的名字
					if(item.getFieldName()!=null){
						String file_name = item.getName();
						System.out.println("-----file表单上传文件名："+file_name);
					}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "success";
	}
	public String toAddGoods() {
		System.out.println("----进入添加商品的方法----------");
		// 一些goods需要初始化的变量
		String gname = null;
		String gdespriction = null;
		String gprice_s = null;
		String gnum_s = null;
		String filename = null;
		String fileid = null;
		// 存放路径初始化
		HttpServletRequest request = ServletActionContext.getRequest();
		String path = request.getSession().getServletContext().getRealPath("/image");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(new File(path));
		factory.setSizeThreshold(10240000);// 设置创建缓冲大小

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setSizeMax(10240);

		try {
			List<FileItem> list = upload.parseRequest(request);
			System.out.println("进入try");
			for (FileItem item : list) {
				if (item.isFormField()) {// 判断是否是文件流
					// 判断字段名，并获得各个表单项的值
					System.out.println("表单项名称：" + item.getFieldName());
					if ("gname".equals(item.getFieldName())) {
						gname = item.getString("utf-8");
					} else if ("gdespriction".equals(item.getFieldName())) {
						gdespriction = item.getString("utf-8");
					} else if ("gprice".equals(item.getFieldName())) {
						gprice_s = item.getString("utf-8");
					} else if ("gnum".equals(item.getFieldName())) {
						gnum_s = item.getString("utf-8");
					}
				} else{//文件表单字段，获取上传文件的名字
					/*String value = item.getName();//会将完整路径名传过来  
                    int start = value.lastIndexOf("\\");  
                    String fileName = value.substring(start+1);  
            //      request.setAttribute(name, fileName);  
                    InputStream in = item.getInputStream();  
                    UploadDomain dao = new UploadDomain();  
                    //item.write(new File(realPath,fileName));  
                    int index = fileName.lastIndexOf(".");  
                    String realFileName = fileName.substring(0,index);  
                    String type = fileName.substring(index+1);  
                    dao.insert(in, realFileName,type,va);//放入到数据库中 */				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();
		}
		System.out.println("也执行到这里了"+gname+gdespriction);
		return "success";
	}
	public void deleteGoods(){
		ServletActionContext.getResponse().setCharacterEncoding("utf-8");
		ServletActionContext.getResponse().setContentType("text/html; charset=utf-8");
		String goodsid = ServletActionContext.getRequest().getParameter("goodsid");
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		try {
			out = response.getWriter();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("---goodsid:"+goodsid);
		int gid = Integer.parseInt(goodsid.trim());
		int result = ps.deleteGoods(gid);
		if(result!=0){
			out.print("删除成功");
		}else{
			out.print("删除失败");
		}
		
		
	}
}
